package com.example.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.common.Result;
import com.example.entity.Hotel;
import com.example.entity.Params;
import com.example.entity.Reserve;
import com.example.mapper.ReserveMapper;
import com.example.service.HotelService;
import com.example.service.ReserveService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: PengFei.He
 * @Date: 2024/11/6 19:59
 * @Function:
 */

@RestController
@RequestMapping("/reserve")
public class ReserveController {

    private static final Logger log = LoggerFactory.getLogger(ReserveController.class);

    @Resource
    ReserveMapper reserveMapper;
    @Autowired
    ReserveService reserveService;
    @Autowired
    HotelService hotelService;

    @GetMapping("/search")
    public Result findBySearch(Params params){
        //1.开启分页
        PageHelper.startPage(params.getPageNum(),params.getPageSize());
        //2.查询信息
        List<Reserve> list = reserveService.findBySearch(params);
        //3.封装对象
        PageInfo<Reserve> info = PageInfo.of(list);
        return Result.success(info);
    }


    // 酒店预定功能
    @PostMapping
    public Result save(@RequestBody Reserve reserve){
        //处理酒店房间数量问题
        Hotel hotel = hotelService.getById(reserve.getHotelId());
        if (hotel.getNum()  == 0){
            return Result.error("酒店房间已满,请预定其他酒店！");
        }

        //酒店预定的逻辑
        reserve.setTime(DateUtil.now());
        reserveMapper.insert(reserve);// 自动将hotelId和userId也一起入库了

        //酒店房间数量减1
        hotel.setNum(hotel.getNum()-1);
        hotelService.updateById(hotel);


        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result del(@PathVariable Integer id){
        reserveService.removeById(id);
        return Result.success();
    }
}
